//
//  StatusPictureCell.swift
//  SinaWeiBo
//
//  Created by gxiangzi on 15/9/8.
//  Copyright © 2015年 hqu. All rights reserved.
//

import UIKit
import SDWebImage

private let StatusPictureViewCellID = "StatusPictureViewCellID"

// 选中照片的通知
let StatusPictureViewSelectedPhotoNotification = "StatusPictureViewSelectedPhotoNotification"
// 选中图片的索引
let StatusPictureViewSelectedIndexPathKey = "StatusPictureViewSelectedIndexPathKey"
/// 选中照片 URL Key
let StatusPictureViewPhotoURLKey = "StatusPictureViewPhotoURLKey"

class StatusPictureView: UICollectionView {
    
    var statusViewModel: StatusViewModel? {
        didSet {
           
            sizeToFit()
            
            // 刷新数据
            reloadData()
        }
    }
    
    override func sizeThatFits(size: CGSize) -> CGSize {

        return calcViewSize()
    }
    
    func calcViewSize() -> CGSize {
        
        let layout = collectionViewLayout as! UICollectionViewFlowLayout        
        layout.itemSize = CGSize(width: GXStatusPictureItemWidth, height: GXStatusPictureItemWidth)
        
       
        // 根据配图来计算 item 的个数
        let count = statusViewModel?.thumbnail?.count ?? 0
        
        if count == 0 {
            
            return CGSizeZero
            
        } else if count == 1 {
            
            // TODO: - 临时返回一个大小
            var size = CGSize(width: 150, height: 150)
            
            let key = statusViewModel!.thumbnail![0].absoluteString
            
            if let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key)
            {
                size = image.size
            }
            
            // 单张图片的时候，设置大小
            layout.itemSize = size
            
            // 单独处理过宽或者过窄的图片
            size.width = size.width < 40 ? 40 : size.width
            size.width = size.width > 300 ? 300 : size.width
            
            return size
            
        } else if count == 4 {
        
            let w = 2 * GXStatusPictureItemWidth + GXStatusPictureItemMargin
            
            return CGSize(width: w, height: w)
            
        } else {
            /*
                2.3
                5.6.
                7.8.9
            */
            let rows = CGFloat((count - 1) / Int(GXStatusPictureMaxCount) + 1)
            
            let w = GXStatusPictureMaxWidth
            
            let h = rows * GXStatusPictureItemWidth + (rows - 1) * GXStatusCellMargin
            
            return CGSize(width: w, height: h)
            
        }
    }
    
    
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        super.init(frame: frame, collectionViewLayout: UICollectionViewFlowLayout())
        backgroundColor = UIColor.lightGrayColor()
        
         let layout = collectionViewLayout as! UICollectionViewFlowLayout
        layout.minimumInteritemSpacing = GXStatusPictureItemMargin
        layout.minimumInteritemSpacing = GXStatusPictureItemMargin
        
        dataSource = self
        delegate = self
        // 注册一个cell
        registerClass(StatusPictureCell.self, forCellWithReuseIdentifier: StatusPictureViewCellID)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}

extension StatusPictureView: UICollectionViewDataSource,UICollectionViewDelegate {
    
    // 获得点击到那张图片
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
    
        // 第一：需要传递 此一组的数值
        // 第二：需要传递 点击的是第几张图片
        NSNotificationCenter.defaultCenter().postNotificationName(StatusPictureViewSelectedPhotoNotification, object: nil, userInfo: [StatusPictureViewPhotoURLKey:statusViewModel!.bmiddleURLs!,StatusPictureViewSelectedIndexPathKey:indexPath])
        
    }
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return statusViewModel?.thumbnail?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell
    {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(StatusPictureViewCellID, forIndexPath: indexPath) as! StatusPictureCell
        
        cell.imageUrl = statusViewModel!.thumbnail![indexPath.row]
        
        return cell
    }
}

// 配图视图的 cell
private class StatusPictureCell:UICollectionViewCell {
    
    var imageUrl : NSURL? {
        didSet {
            
            iconView.sd_setImageWithURL(imageUrl)
   
        }
    }

    override  init(frame: CGRect) {
        super.init(frame: frame)
        addSubview(iconView)
        
        iconView.ff_Fill(self)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private lazy var iconView:UIImageView = {
        let iv = UIImageView()
        
        iv.contentMode = UIViewContentMode.ScaleAspectFit
        iv.clipsToBounds = true
        return iv
    }()
    
}
